package com.level.system.task;

import com.alibaba.fastjson.JSON;
import com.level.system.entity.emr.DATA_HZ;
import com.level.system.service.EmrParseService;
import com.level.system.util.EmrParserUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class HZ_BCJLThread extends Thread {

    private List<DATA_HZ> taskList;
    private EmrParseService emrService;
    private final Logger log = LoggerFactory.getLogger(HZ_BCJLThread.class);

    public HZ_BCJLThread(List<DATA_HZ> list, EmrParseService service) {
        this.taskList = list;
        this.emrService = service;
    }

    /**
     * 获取元素内容
     *
     * @param element
     * @return
     */
    private static String getMRXmlText(Element element) {
        String levelchapter = element.attr("levelchapter");
        Map<String, Object> chapterMap = JSON.parseObject(levelchapter);
        // 获取默认值属性
        String chapterId = chapterMap.get("chapterId").toString();
        // 1移除levelplugins=nodeblock
        element.select("span[levelplugins='nodeblock']").remove();
        // 2提取leftbrackets、rightbrackets节点内容

        // 替换空格
        String tempHtml = element.html();
        tempHtml = tempHtml.replaceAll("&nbsp;", " ");
        element.html(tempHtml);

        String text = element.text().trim();
        // System.out.println("element.html " + element.html());
        if (text.length() > 0) {
            // 去掉[
            text = text.substring(1, text.length());
            // 去掉]
            if (text.length() > 0) {
                text = text.substring(0, text.length() - 1);
            }
        }
        // System.out.println("chapterId " + chapterMap);
        // System.out.println("text " + text);
        return text.trim();
    }

    @Override
    public void run() {
        handleTask(this.taskList);
    }

    private void handleTask(List<DATA_HZ> list) {
        List<Map<String, Object>> paramList = new ArrayList<>();
        Map<String, Object> paramMap = new HashMap<>();

        for (Iterator it = list.iterator(); it.hasNext(); ) {
            // 1获取病历对象
            DATA_HZ emrParser = (DATA_HZ) it.next();
            // 2获取病历html
            String html = new String(emrParser.getMRCONTENT());
            // 3获取病历解析结果
            Map<String, Object> map = getBcjl(html);
            map.put("jgid", emrParser.getJGID());
            map.put("id", emrParser.getID());
            map.put("mcNo", emrParser.getMCNO());
            map.put("docId", emrParser.getDOCID());
            map.put("mzzy", emrParser.getMZZY());
            map.put("emrType", emrParser.getEMRTYPE());
            map.put("templateType", emrParser.getTEMPLATETYPE());
            map.put("archiveTime", emrParser.getARCHIVETIME());
            map.put("rysj", emrParser.getRYSJ());
            map.put("cysj", emrParser.getCYSJ());

            map.put("name", emrParser.getNAME());
            map.put("sex", emrParser.getSEX());
            map.put("birthday", emrParser.getBIRTHDAY());

            map.put("creater", "dba");
            map.put("createTime", new Date());

            map.put("cjr", emrParser.getCJR());
            map.put("cjsj", emrParser.getCJSJ());
            map.put("xgr", emrParser.getXGR());
            map.put("xgsj", emrParser.getXGSJ());
            map.put("jlsj", emrParser.getJLSJ());

            paramList.add(map);
        }
        paramMap.put("list", paramList);
        log.info("==========================病程记录保存："+paramMap);
        emrService.batchSaveHZ(paramMap);
    }

    /**
     * 获取病程记录
     *
     * @param html
     * @return
     */
    public Map<String, Object> getBcjl(String html) {
        Map<String, Object> map = new HashMap<>();
        map.put("state", "0");

        // 病历文书内容
        Document doc = Jsoup.parseBodyFragment(html);

        // 获取所有符合条件的div标签域
        Elements lcs = doc.select("span[levelchapter]");
        for (Iterator it = lcs.iterator(); it.hasNext(); ) {
            Element lc = (Element) it.next();
            String levelchapter = lc.attr("levelchapter");
            // 转成map对象
            Map<String, Object> chapterMap = JSON.parseObject(levelchapter);
            // 获取默认值属性
            String chapterId = chapterMap.get("chapterId").toString();
            if ("MR-1001-1003-1022".equals(chapterId)) {
                // 病例特点
                map.put("casecharacteristics", EmrParserUtil.subStr(getMRXmlText(lc), 1000));
            } else if ("MR-1001-1003-1025".equals(chapterId)) {
                // 诊断依据
                map.put("diagnosticbasis", EmrParserUtil.subStr(getMRXmlText(lc), 1000));
            } else if ("MR-1001-1003-1003".equals(chapterId)) {
                // 治疗计划
                map.put("treatmentplanning", EmrParserUtil.subStr(getMRXmlText(lc), 4000));
            }
        }

        //移除头尾
        doc.select("span[levelplugins='leftbrackets'],span[levelplugins='rightbrackets']").remove();
        Elements lps = doc.select("span[levelplugins]");
        for (int i = 0; i < lps.size(); i++) {
            lps.get(i).html(lps.get(i).text());
        }
        //第2个tr第1个td
        Elements tds = doc.select("table tbody tr").eq(1).select("td").eq(0);

        if (tds.size() > 0) {
            map.put("content", EmrParserUtil.subStr(tds.get(0).text(), 4000));
        }

        return map;
    }
}
